package snu.bi.MSAgent;

import snu.bi.MSAgent.ActRecog.ActionService;
import snu.bi.MSAgent.DB.MSADBHandler;
import snu.bi.MSAgent.Estimator.WeightEstimator;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;
import java.util.TimeZone;
import snu.bi.MSAgent.valuepopup;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.content.DialogInterface.OnDismissListener;
import android.widget.TextView;

public class MSAgentActivity extends Activity implements OnDismissListener, Observer {
    /** Called when the activity is first created. */
	TextView values[];
	Button recom[];
	Button menuinput;
//<<<<<<< .mine
//	TextView today_cal_in, today_cal_con;
	ComponentName svc;
//=======
	ComponentName aService;
	TextView today_cal_in, today_cal_con;
//>>>>>>> .r22
	
	/* Variables for update ##########################*/
	private int forMinuteCheck = -1;
	private static MSAgentActivity sInstance = null;
	boolean needUpdate = false;
	public static MSAgentActivity getInstance(){
		return MSAgentActivity.sInstance;
	}	
	/*################################################*/
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        TimeZone timezone = TimeZone.getTimeZone("Etc/GMT-9");
        TimeZone.setDefault(timezone);

        values = new TextView[5];
        values[0] = (TextView)findViewById(R.id.weight_value);
        values[1] = (TextView)findViewById(R.id.height_value);
        values[2] = (TextView)findViewById(R.id.age_value);
        values[3] = (TextView)findViewById(R.id.sex_value);
        values[4] = (TextView)findViewById(R.id.bmi_value);
        
        today_cal_in = (TextView)findViewById(R.id.intake_value);
        today_cal_con  = (TextView)findViewById(R.id.con_value);
        
        recom = new Button[2];
        recom[0] = (Button)findViewById(R.id.recom_menu);
        recom[1] = (Button)findViewById(R.id.recom_exer);
                
        menuinput = (Button)findViewById(R.id.menuinput);
        
        //aService = startService(new Intent(this, ActionService.class));                
        
        MSADBHandler tempdb = MSADBHandler.open(this.getApplicationContext());
        
        /*-----------------------------------------------

        long start = Long.parseLong("1322470812668") - (48*60*1000);
        
        // 달리기    	
        for(int i = 0; i < (3*60); i++){	// 3시간 동안 달리기
	        ContentValues newValues = new ContentValues();
			newValues.put("time", String.valueOf(start += i*60000));
			newValues.put("act_type", ActionService.ACTION_RUN);
			tempdb.insert("excer_table", null, newValues);
    	}
        //-------------3시간
        for(int i = 0; i < (3*60); i++){	// 3시간 동안 정지
	        ContentValues newValues = new ContentValues();
			newValues.put("time", String.valueOf(start += i*60000));
			newValues.put("act_type", ActionService.ACTION_STAY);
			tempdb.insert("excer_table", null, newValues);
    	}
        //-------------6시간        
        for(int i = 0; i < (3*60); i++){	// 3시간 동안 걷기
	        ContentValues newValues = new ContentValues();
			newValues.put("time", String.valueOf(start += i*60000));
			newValues.put("act_type", ActionService.ACTION_STAY);
			tempdb.insert("excer_table", null, newValues);
    	}
        //-------------9시간
        for(int i = 0; i < (3*60); i++){	// 3시간 동안 정지
	        ContentValues newValues = new ContentValues();
			newValues.put("time", String.valueOf(start += i*60000));
			newValues.put("act_type", ActionService.ACTION_STAY);
			tempdb.insert("excer_table", null, newValues);
    	}
        //-------------12시간
        for(int i = 0; i < (3*60); i++){	// 3시간 동안 뛰기
	        ContentValues newValues = new ContentValues();
			newValues.put("time", String.valueOf(start += i*60000));
			newValues.put("act_type", ActionService.ACTION_STAY);
			tempdb.insert("excer_table", null, newValues);
    	}
        //-------------15시간
        for(int i = 0; i < (3*60); i++){	// 3시간 동안 정지
	        ContentValues newValues = new ContentValues();
			newValues.put("time", String.valueOf(start += i*60000));
			newValues.put("act_type", ActionService.ACTION_STAY);
			tempdb.insert("excer_table", null, newValues);
    	}
        //-------------18시간
        for(int i = 0; i < (3*60); i++){	// 3시간 동안 뛰기
	        ContentValues newValues = new ContentValues();
			newValues.put("time", String.valueOf(start += i*60000));
			newValues.put("act_type", ActionService.ACTION_STAY);
			tempdb.insert("excer_table", null, newValues);
    	}
        //-------------21시간
        for(int i = 0; i < (3*60); i++){	// 3시간 동안 걷기
	        ContentValues newValues = new ContentValues();
			newValues.put("time", String.valueOf(start += i*60000));
			newValues.put("act_type", ActionService.ACTION_STAY);
			tempdb.insert("excer_table", null, newValues);
    	}
        
		-----------------------------------------------*/
        
        tempdb.close();
                
        userinfodisplay();
        svc = startService(new Intent(this, snu.bi.MSAgent.ActRecog.ActionService.class));
        Log.i("svm_test", "Svc Started");
        
        MSAgentActivity.sInstance = this;
        
        UpdateThread updateThread = new UpdateThread(this);
        updateThread.start();
        
    }
    
    public void setObservable(ActionService as){
    	as.setObserver(this);
    }
    
    public void onDestroy(){
    	stopService(new Intent(this, svc.getClass()));
    	super.onDestroy();
    }
    
    public void value_click(View view) {    	
    	valuepopup vp;
    	if(view == values[0]) vp = new valuepopup(this, 0);
    	else if(view == values[1]) vp = new valuepopup(this, 1);
    	else if(view == values[2]) vp = new valuepopup(this, 2);
    	else vp = new valuepopup(this, 3);
		vp.setOnDismissListener(this);
		vp.show();
    }
    public void recom_click(View view) {    	
    	Intent intsub;
    	if(view==recom[0]) {
    		intsub = new Intent(this, MenuActivity.class);    		
    		startActivity(intsub);
    	}
    	else if(view==recom[1]) {
    		intsub = new Intent(this, ExerActivity.class);    		
    		startActivity(intsub);
    	}    	
    }
    public void menuinput_click(View view) {
    	Intent intsub = new Intent(this, MIActivity.class);    	
    	startActivity(intsub);
    }        
    public void userinfodisplay() {
    	MSADBHandler tempdb = MSADBHandler.open(this.getApplicationContext());
    	
    	System.out.println(new java.util.Date().getTime());
		
		String maxtime = getmaxtimeindb(tempdb,"weight_table");
		Cursor cur0 = tempdb.rawQuery("select * from weight_table where time='"+maxtime+"'");
		maxtime = getmaxtimeindb(tempdb,"height_table");
		Cursor cur1 = tempdb.rawQuery("select * from height_table where time='"+maxtime+"'");
		maxtime = getmaxtimeindb(tempdb,"age_table");
		Cursor cur2 = tempdb.rawQuery("select * from age_table where time='"+maxtime+"'");
		maxtime = getmaxtimeindb(tempdb,"sex_table");
		Cursor cur3 = tempdb.rawQuery("select * from sex_table where time='"+maxtime+"'");
		maxtime = getmaxtimeindb(tempdb,"bmi_table");
		Cursor cur4 = tempdb.rawQuery("select * from bmi_table where time='"+maxtime+"'");
		
		cur0.moveToFirst();cur1.moveToFirst();cur2.moveToFirst();cur3.moveToFirst();cur4.moveToFirst();		
		
		if(cur0.getCount()>0) values[0].setText(Double.toString(cur0.getDouble(1)) + " kg");
		else values[0].setText("Touch here");
		if(cur1.getCount()>0) values[1].setText(Double.toString(cur1.getDouble(1)) + " cm");
		else values[1].setText("Touch here");
		if(cur2.getCount()>0) values[2].setText(Integer.toString(cur2.getInt(1)) + " years");
		else values[2].setText("Touch here");
		if(cur4.getCount()>0) values[4].setText(Double.toString(cur4.getDouble(1)).substring(0, 6));
		else values[4].setText(" 0 ");
		if(cur3.getCount()>0) {
			if(cur3.getInt(1) == 0) values[3].setText("Man");		
			else values[3].setText("Woman");
		}
		else values[3].setText("Touch here");
		
		cur0.close();
		cur1.close();
		cur2.close();
		cur3.close();
		cur4.close();
		tempdb.close();
    }
    private String getmaxtimeindb(MSADBHandler sdb, String tablename) {    	
		Cursor cur = sdb.rawQuery("SELECT MAX(time) FROM "+tablename);
		cur.moveToFirst();
		String re = cur.getString(0);
		cur.close();
		return re;
	}
    void todaycaldisplay() {
    	double in, out;
		MSADBHandler tempdb = MSADBHandler.open(this.getApplicationContext());
		WeightEstimator we = new WeightEstimator(tempdb);
		
		in = we.calculateIntakeCalories(1);
		out = we.burnedUpCalories(1);
		
		tempdb.close();
    	
    	today_cal_in.setText(Double.toString(Math.round(in*100)/100)+" kcal");
    	today_cal_con.setText(Double.toString(Math.round(out*100)/100)+" kcal");
    }
    
	public void onDismiss(DialogInterface dialog) {
		// TODO Auto-generated method stub
    	userinfodisplay();
    	stopService(new Intent(this, snu.bi.MSAgent.ActRecog.ActionService.class));
	}	
	@Override
	public void onResume() {
		super.onResume();
		todaycaldisplay();		
		//this.recom_click(recom[0]);
	}

	@Override
	public void update(Observable arg0, Object arg1) {
		// 얘가 빨리 리턴을 해야 Service가 하던 일에 복귀해서 할 수 있으므로, 플래그 셋팅만 하고 UpdateThread가 텍스트 설정
		// TODO Auto-generated method stub
		int minuteNow = -1;
		Calendar now = Calendar.getInstance();
		if(this.forMinuteCheck != (minuteNow = now.get(Calendar.MINUTE))){
			this.forMinuteCheck = minuteNow;
			// perfoming
			Log.d("FROM SERVICE:", "time: " + minuteNow + "\tupdate called!!");
			this.todaycaldisplay();
			this.needUpdate = true;
		}
	}
}

class UpdateThread extends Thread{
	
	private MSAgentActivity target = null;
	
	public UpdateThread(MSAgentActivity target){
		this.target = target;
	}
	
	public void run(){
		try {
			
//			this.target.todaycaldisplay();
			this.target.needUpdate = false;
			UpdateThread.sleep(1000);	// sleep for 1 minute
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
